package cn.edu.lcu.cs.javaweb.dao;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import cn.edu.lcu.cs.javaweb.entity.User;
import sun.security.util.Length;

/**
 * UserDao的实现，用内存中的列表模拟数据库
 * 
 * @author Ling
 *
 */
public class UserDaoImpl implements UserDao {
	// 用内存中的用户列表模拟用户的增删改查操作
	private static List<User> users;
	private static final int LENGTH = 10; // 初始人员数量

	/**
	 * 静态代码块，初始化用户列表
	 */
	static {
		users = new ArrayList<User>();
		Random random = new Random();
		for (int i = 0; i < LENGTH; i++) {
			Long r = (long) random.nextInt(100);
			User user = new User(r, "user" + r, LocalDate.of(1949, 10, 1), "123", r + "@xxx.com",
					"123456789", random.nextBoolean() ? "admin" : "common");
			users.add(user);
		}
	}

	@Override
	public User findById(Long id) {
		return users.stream().filter(user -> user.getId() == id).findFirst().orElse(null);
	}

	@Override
	public List<User> findByUsername(String username) {
		return users.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
	}

	@Override
	public User authenticate(String username, String password) {
		return users.stream().filter(user -> user.getUsername().equals(username) && user.getPassword().equals(password))
				.findFirst().orElse(null);
	}

	@Override
	public User save(User user) {
		if (user != null) {
			users.add(user);
		}
		return user;
	}

	@Override
	public int delete(Long id) {
		User user = findById(id);
		if (user != null) {
			users.remove(user);
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int update(User user) {
		if (user == null) {
			return 0;
		}
		User userToUpdate = findById(user.getId());
		if (userToUpdate == null) {
			return 0;
		}
		// 直接赋值，不再逐个属性赋值了
		userToUpdate = user;
		return 1;
	}

	@Override
	public List<User> findAll() {
		return users;
	}

	@Override
	public long count() {
		// TODO Auto-generated method stub
		return 0;
	}

}
